@page "/device-management"
@using AIoTGateway_UI.Data
@using AIoTGateway_UI.Data.Models
@using Microsoft.EntityFrameworkCore
@using AIoTGateway_UI.Services
@inject IoTDbContext DbContext
@* @inject MQTTService MqttService  // 这条语句是为了注入MQTTService，是它导致/home面无法正常显示的原因。 *@

@implements IDisposable

@rendermode InteractiveServer

<h3>车间设备</h3>
<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>车间ID</th>
            <th>设备名称</th>
            <th>设备类型</th>
            <th>设备状态1</th>
            <th>设备状态2</th>
            <th>设备描述</th>
            <th>设备SN</th>
            <th>设备操作</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var device in devices)
        {
            <tr>
                <td>@device.Id</td>
                <td>@device.WorkshopId</td>
                <td>@device.Name</td>
                <td>@device.Type</td>
                <td>@device.Status1</td>
                <td>@device.Status2</td>
                <td>@device.Description</td>
                <td>@device.DeviceSN</td>
                <td>
                    <button @onclick="() => EditDevice(device.Id)">编辑</button>
                    <button @onclick="() => DeleteDevice(device.Id)">删除</button>
                    <button @onclick="() => UpdateStatus(device.Id)"
                    style="background-color: @(device.Status1 == 0 ? "#808080" : "#007bff"); color: white;">
                        @(device.Status1 == 0 ? "已关闭" : "已启动")
                    </button>
                </td>
            </tr>
        }
    </tbody>
</table>

<h3>新增设备与更新</h3>
@* <input type="number" @bind="newDevice.Id" placeholder="ID" /> *@
@* <input type="number" @bind="newDevice.WorkshopId" placeholder="车间ID" /> *@
<input type="number" @bind="newDevice.WorkshopId" placeholder="车间ID" />
<input type="text" @bind="newDevice.Name" placeholder="设备名称" />
<input type="text" @bind="newDevice.Type" placeholder="设备类型" />
<input type="number" @bind="newDevice.Status1" placeholder="设备状态1" />
<input type="number" @bind="newDevice.Status2" placeholder="设备状态2" />
<input type="text" @bind="newDevice.Description" placeholder="设备描述" />
<input type="text" @bind="newDevice.DeviceSN" placeholder="设备SN" />
<button type="button" @onclick="AddDevice">添加</button>
<button type="button" @onclick="Update">更新</button>

@code {
    private List<Device> devices;
    // private Device newDevice = new Device();
    private Device newDevice = new Device{
        WorkshopId = 1  // 设置默认值为0或其他有效车间ID 
    };

    private System.Threading.Timer _timer;

    protected override async Task OnInitializedAsync()
    {
        devices = DbContext.Devices.ToList();

        try
        {
            // 初始化定时器，每隔5秒刷新设备列表
            _timer = new System.Threading.Timer(async _ =>
            {
                Console.WriteLine("Timer triggered");
                
            }, null, 0, 1000); // 0表示立即开始，5000表示每隔5秒执行一次
        }catch(Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }

    #if false
    private void AddDevice()
    {
        DbContext.Devices.Add(newDevice);
        DbContext.SaveChanges();
        devices = DbContext.Devices.ToList();
        newDevice = new Device();
    }
    #else
    private void AddDevice()
{
    newDevice.Id = 0; // 设置默认值为0或其他有效车间ID
    newDevice.WorkshopId = 1; // 设置默认值为0或其他有效车间ID
    try 
    {
        DbContext.Devices.Add(newDevice);
        DbContext.SaveChanges(); // 主要修改点：添加异常捕获
        devices = DbContext.Devices.ToList();

        newDevice = new Device();
    }
    catch (Exception ex)
    {
        // 建议补充日志记录：_logger.LogError(ex, "设备添加失败");
        devices = DbContext.Devices.ToList(); // 刷新数据
       newDevice = new Device(); // 重置表单
    }
}
#endif

#if false
    private void Update()
    {
        DbContext.Devices.Update(newDevice);
        DbContext.SaveChanges();
        devices = DbContext.Devices.ToList();
        newDevice = new Device();
    }
    #else
    private void Update(){
    try 
    {
        DbContext.Devices.Update(newDevice);
        DbContext.SaveChanges(); // 主要修改点：添加异常捕获
        devices = DbContext.Devices.ToList();        
    }
    catch (Exception ex)
    {
        // 建议补充日志记录：_logger.LogError(ex, "设备更新失败");
        devices = DbContext.Devices.ToList(); // 刷新数据     
        
    }
}
    #endif

    private void DeleteDevice(int id)
    {
        var device = DbContext.Devices.Find(id);
        if (device != null)
        {
            DbContext.Devices.Remove(device);
            DbContext.SaveChanges();
            devices = DbContext.Devices.ToList();
        }
    }

    private void EditDevice(int id)
    {
        var device = DbContext.Devices.Find(id);
        if (device != null)
        {
            newDevice = device;
        }
    }    

    #if true
    private void UpdateStatus(int id)
    {
        // 这里需要添加更新逻辑，比如调用API或触发状态更新
        var device = DbContext.Devices.Find(id);
        if (device != null)
        {
            device.Status1 = (device.Status1 == 0 ? 1 : 0);
            DbContext.Devices.Update(device);
            DbContext.SaveChanges();
            devices = DbContext.Devices.ToList();
        }
    }
    #else
    // 重构后的UpdateStatus方法
private void UpdateStatus(int id)
{
    var device = DbContext.Devices.Find(id);
    if (device == null) return;
    try 
    {
        newDevice = device;
        newDevice.Status1 = (device.Status1 == 0 ? 1 : 0);
        
        DbContext.Devices.Update(newDevice);
        DbContext.SaveChanges(); // 主要修改点：添加异常捕获
        devices = DbContext.Devices.ToList();
        newDevice = new Device();
    }
    catch (Exception ex)
    {
        // 建议补充日志记录：_logger.LogError(ex, "状态更新失败");
        newDevice.Status1 = device.Status1; // 回滚状态
        isActive = !isActive; // 同步恢复UI状态
        devices = DbContext.Devices.ToList(); // 刷新数据
    }
}
    #endif      

    public void Dispose(){
        _timer?.Dispose();
    }
}

